import React, {Component} from 'react';

class FetchUpload extends Component {
    constructor(props) {
        super(props);
        this.fileInput = React.createRef();
    }

    upload = () => {
        const data = new FormData();
        data.append('file', this.fileInput.current.files[0]);  //相当于 input:file 中的name属性
        fetch('http://127.0.0.1:3001/file/upload', {
            method: 'POST',
            body: data
        }).then(response => console.log(response))
    };


    render() {
        return (
            <div>
                <input type="file" name='file' ref={this.fileInput}/>
                <input type="button" value="上传" onClick={this.upload}/>
            </div>
        )
    }
}

export default FetchUpload;

/*
* 原理是取出input:file中的文件并与input:file的name属性组合成键值对加入到FormData对象中封装成指定数据对象，通过fetch或者Axios或者Ajax传给后台
*/